package com.example.yian.controller;

import com.example.yian.entity.SecurityRisk;
import com.example.yian.entity.SecurityRiskReport;
import com.example.yian.service.SecurityRiskReportService;
import com.example.yian.service.SecurityRiskService;
import com.example.yian.service.WeChatAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.time.Instant;
import java.time.LocalDate;
import java.util.*;

@RestController
public class SecurityRiskController {

    @Autowired
    private SecurityRiskService securityRiskService;

    @Autowired
    private WeChatAuthService weChatAuthService;

    @Autowired
    private SecurityRiskReportService reportService;

    @PostMapping("/addSecurityRisks")
    public Map<String, Object> handleAddSecurityRisk(@RequestHeader("Authorization") String token, @RequestBody Map<String, String> requestBody) {
        Map<String, Object> response = new HashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);
        if (userIdOpt.isPresent()) {
            Long userId = userIdOpt.get();
            String image = requestBody.get("image");
            String chatId = requestBody.get("chat_id");
            String textId = requestBody.get("text_id");
            String supplementContents = requestBody.get("supplement_contents");
            SecurityRisk securityRisk = securityRiskService.addSecurityRisk(image, chatId, textId, supplementContents, userId);
            response.put("code", 200);
            response.put("msg", "成功");
            response.put("data", Map.of("risks_id", securityRisk.GetId()));
        } else {
            response.put("code", 401);
            response.put("msg", "未授权");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
        }
        return response;
    }

    @GetMapping("/getSecurityRisks")
    public Map<String, Object> getSecurityRiskWithDetails(@RequestParam Long risksId) {
        Map<String, Object> response = new HashMap<>();
        Optional<SecurityRisk> riskOpt = securityRiskService.getSecurityRiskWithDetails(risksId);
        if (riskOpt.isPresent()) {
            response.put("code", 200);
            response.put("msg", "成功");
            response.put("data", riskOpt.get());
        } else {
            response.put("code", 404);
            response.put("msg", "未找到记录");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
        }
        return response;
    }

    /**
     * 分页获取指定用户的隐患列表
     * @param requestParams 请求参数，包含分页信息及用户ID
     * @param token 访问令牌
     * @return 分页数据及状态信息
     */
    @PostMapping("/getRiskLists")
    public Map<String, Object> getRiskLists(
            @RequestBody Map<String, Object> requestParams,
            @RequestHeader("Authorization") String token) {
        Map<String, Object> response = new LinkedHashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);

        if (!userIdOpt.isPresent()) {
            response.put("code", 401);
            response.put("msg", "未授权");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
            return response;
        }
        Long userId = userIdOpt.get();
        // 从请求体中提取分页参数
        Integer pageNum = (Integer) requestParams.getOrDefault("page", 1);
        Integer pageSize = (Integer) requestParams.getOrDefault("size", 1000);
        String  startTime = (String) requestParams.getOrDefault("startTime", "2024-08-03");
        if (Objects.equals(startTime, "")) {
            startTime = "2024-05-03";
        }
        String endTime = (String) requestParams.getOrDefault("endTime", "2099-08-15");
        if (Objects.equals(endTime, "")) {
            endTime = "2099-08-15";
        }

        Page<SecurityRisk> page = new Page<>(pageNum, pageSize);
        IPage<SecurityRisk> riskPage = securityRiskService.getRiskListsByUserId(userId, pageNum, pageSize, startTime,endTime);
        response.put("code", 200);
        response.put("msg", "成功");
        response.put("time", Instant.now().toEpochMilli());
        response.put("total", riskPage.getTotal());

        //重新拿取一把
        List<SecurityRisk> risks = riskPage.getRecords();
        List<Map<String, Object>> dataWithExtraFields = new ArrayList<>();
        for (SecurityRisk risk : risks) {
            Map<String, Object> dataItem = new HashMap<>();
            dataItem.put("id", risk.GetId()); // 假设 id 是一个 Long 类型的字段
            dataItem.put("userId", risk.GetUserId()); // 假设 otherField 是另一个 Long 类型的字段
            dataItem.put("image", risk.getImage());
            dataItem.put("chatId", risk.GetChatId());
            dataItem.put("textId", risk.getTextId());
            dataItem.put("supplementContents", risk.GetSupplementContents());
            dataItem.put("createdAt", risk.GetCreatedAt());
            dataItem.put("updatedAt", risk.GetUpdatedAt());
            dataWithExtraFields.add(dataItem);
        }
        response.put("data",dataWithExtraFields);

        return response;
    }


    @PostMapping("/weeklyRiskCounts")
    public ResponseEntity<Map<String, Object>> getWeeklyRiskCounts(
            @RequestHeader("Authorization") String token) {
        Map<String, Object> response = new LinkedHashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);

        if (!userIdOpt.isPresent()) {
            response.put("code", 401);
            response.put("msg", "未授权");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
            // return  ResponseEntity.ok(response);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
        Long userId = userIdOpt.get();
        Map<LocalDate, Long> countsByDay = securityRiskService.countRisksByDayOfWeekForUser(userId);
        // 将LocalDate转换为字符串，便于前端处理（可选，取决于前端需求）
        Map<String, Long> formattedCounts = new HashMap<>();
        countsByDay.forEach((date, count) -> formattedCounts.put(date.toString(), count));
        response.put("code", 200);
        response.put("msg", "成功");
        response.put("data", formattedCounts);
        return ResponseEntity.ok(response);
    }

}
